package com.suep.data_analysis.controller;

import com.suep.data_analysis.dto.CharacterStatsDto;
import com.suep.data_analysis.dto.DamageCalculationRequestDto;
import com.suep.data_analysis.dto.DamageCalculationResultDto;
import com.suep.data_analysis.dto.DamageRangeResultDto;
import com.suep.data_analysis.dto.UserConfigDetailDto;
import com.suep.data_analysis.model.AgentSkills;
import com.suep.data_analysis.service.CharacterStatsCalculationService;
import com.suep.data_analysis.service.DamageCalculationService;
import com.suep.data_analysis.service.UserConfigService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色属性面板控制器
 */
@RestController
@RequestMapping("/api/character-stats")
@AllArgsConstructor
@CrossOrigin(origins = "*")
public class CharacterStatsController {
    private final CharacterStatsCalculationService characterStatsCalculationService;
    private final DamageCalculationService damageCalculationService;
    private final UserConfigService userConfigService;

    /**
     * 获取角色最终属性面板
     * 
     * @param userConfigId 用户配置ID
     * @param userId 用户ID（用于验证）
     * @return 角色最终属性
     */
    @GetMapping("/{userConfigId}")
    public ResponseEntity<CharacterStatsDto> getCharacterStats(
            @PathVariable String userConfigId,
            @RequestParam String userId
    ) {
        try {
            // 调用现有的UserConfigService获取用户配置详情
            UserConfigDetailDto userConfig = userConfigService.getConfigDetailById(userConfigId);
            if (userConfig == null || !userConfig.getUserId().equals(userId)) {
                return ResponseEntity.notFound().build();
            }

            // 计算最终属性
            CharacterStatsDto finalStats = characterStatsCalculationService.calculateFinalStats(userConfig);
            return ResponseEntity.ok(finalStats);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取角色详细信息和最终属性面板
     * 
     * @param userConfigId 用户配置ID
     * @param userId 用户ID（用于验证）
     * @return 角色详细信息和最终属性
     */
    @GetMapping("/{userConfigId}/detail")
    public ResponseEntity<CharacterDetailResponse> getCharacterDetail(
            @PathVariable String userConfigId,
            @RequestParam String userId
    ) {
        try {
            // 调用现有的UserConfigService获取用户配置详情
            UserConfigDetailDto userConfig = userConfigService.getConfigDetailById(userConfigId);
            if (userConfig == null || !userConfig.getUserId().equals(userId)) {
                return ResponseEntity.notFound().build();
            }

            // 计算最终属性
            CharacterStatsDto finalStats = characterStatsCalculationService.calculateFinalStats(userConfig);

            // 构建响应
            CharacterDetailResponse response = new CharacterDetailResponse();
            response.setUserConfig(userConfig);
            response.setFinalStats(finalStats);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 计算技能伤害
     * 
     * @param userConfigId 用户配置ID
     * @param userId 用户ID（用于验证）
     * @param request 伤害计算请求
     * @return 伤害计算结果
     */
    @PostMapping("/{userConfigId}/damage-calculation")
    public ResponseEntity<DamageCalculationResultDto> calculateDamage(
            @PathVariable String userConfigId,
            @RequestParam String userId,
            @RequestBody DamageCalculationRequestDto request
    ) {
        try {
            // 调用现有的UserConfigService获取用户配置详情
            UserConfigDetailDto userConfig = userConfigService.getConfigDetailById(userConfigId);
            if (userConfig == null || !userConfig.getUserId().equals(userId)) {
                return ResponseEntity.notFound().build();
            }

            // 计算伤害
            DamageCalculationResultDto result = damageCalculationService.calculateDamage(userConfig, request);
            return ResponseEntity.ok(result);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 批量计算多个技能伤害
     * 
     * @param userConfigId 用户配置ID
     * @param userId 用户ID（用于验证）
     * @param skillIds 技能ID列表
     * @param elementType 元素类型
     * @param isCritical 是否考虑暴击
     * @return 伤害计算结果列表
     */
    @GetMapping("/{userConfigId}/damage-comparison")
    public ResponseEntity<List<DamageCalculationResultDto>> compareSkills(
            @PathVariable String userConfigId,
            @RequestParam String userId,
            @RequestParam List<String> skillIds,
            @RequestParam(defaultValue = "以太") String elementType,
            @RequestParam(required = false) Boolean isCritical
    ) {
        try {
            // 调用现有的UserConfigService获取用户配置详情
            UserConfigDetailDto userConfig = userConfigService.getConfigDetailById(userConfigId);
            if (userConfig == null || !userConfig.getUserId().equals(userId)) {
                return ResponseEntity.notFound().build();
            }

            // 批量计算伤害
            List<DamageCalculationResultDto> results = damageCalculationService.calculateMultipleSkills(
                    userConfig, skillIds, elementType, isCritical);
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 计算技能伤害范围（考虑暴击概率）
     * 
     * @param userConfigId 用户配置ID
     * @param userId 用户ID（用于验证）
     * @param skillId 技能ID
     * @param elementType 元素类型
     * @param iterations 模拟次数（默认1000）
     * @return 伤害范围统计
     */
    @GetMapping("/{userConfigId}/damage-range")
    public ResponseEntity<DamageRangeResultDto> calculateDamageRange(
            @PathVariable String userConfigId,
            @RequestParam String userId,
            @RequestParam String skillId,
            @RequestParam(defaultValue = "以太") String elementType,
            @RequestParam(defaultValue = "1000") Integer iterations
    ) {
        try {
            // 调用现有的UserConfigService获取用户配置详情
            UserConfigDetailDto userConfig = userConfigService.getConfigDetailById(userConfigId);
            if (userConfig == null || !userConfig.getUserId().equals(userId)) {
                return ResponseEntity.notFound().build();
            }

            // 创建请求对象
            DamageCalculationRequestDto request = new DamageCalculationRequestDto();
            request.setSkillId(skillId);
            request.setElementType(elementType);
            request.setIsCritical(null); // 随机暴击
            request.setTargetDefense(0.0); // 设置默认目标防御力
            request.setTargetResistance(0.0); // 设置默认目标抗性

            // 计算伤害范围
            DamageRangeResultDto result = damageCalculationService.calculateDamageRange(
                    userConfig, request, iterations);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取角色的可计算伤害的技能列表
     * 
     * @param userConfigId 用户配置ID
     * @param userId 用户ID（用于验证）
     * @return 可计算伤害的技能列表
     */
    @GetMapping("/{userConfigId}/damage-skills")
    public ResponseEntity<List<AgentSkills>> getDamageSkills(
            @PathVariable String userConfigId,
            @RequestParam String userId
    ) {
        try {
            // 调用现有的UserConfigService获取用户配置详情
            UserConfigDetailDto userConfig = userConfigService.getConfigDetailById(userConfigId);
            if (userConfig == null || !userConfig.getUserId().equals(userId)) {
                return ResponseEntity.notFound().build();
            }

            // 获取角色的可计算伤害的技能
            List<AgentSkills> damageSkills = damageCalculationService.getDamageSkills(userConfig.getAgent().getAgentId());
            return ResponseEntity.ok(damageSkills);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 角色详细信息响应类
     */
    public static class CharacterDetailResponse {
        private UserConfigDetailDto userConfig;
        private CharacterStatsDto finalStats;

        // Getters and Setters
        public UserConfigDetailDto getUserConfig() {
            return userConfig;
        }

        public void setUserConfig(UserConfigDetailDto userConfig) {
            this.userConfig = userConfig;
        }

        public CharacterStatsDto getFinalStats() {
            return finalStats;
        }

        public void setFinalStats(CharacterStatsDto finalStats) {
            this.finalStats = finalStats;
        }
    }
} 